package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.RoleDto;
import com.zzyl.entity.Role;
import com.zzyl.entity.RoleResource;
import com.zzyl.mapper.RoleMapper;
import com.zzyl.mapper.RoleResourceMapper;
import com.zzyl.service.RoleService;
import com.zzyl.utils.EmptyUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.google.common.collect.Lists;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;


import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RoleResourceMapper roleResourceMapper;

    @Override
    public PageResponse<RoleVo> findRolePage(RoleDto roleDto, int pageNo, int pageSize) {
        PageHelper.startPage(pageNo, pageSize);
        Page<List<Role>> page = roleMapper.selectPage(roleDto);
        PageResponse<RoleVo> pageResponse = PageResponse.of(page, RoleVo.class);
        return pageResponse;
    }

    @Override
    public void createRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.insert(role);
    }

    @Override
    public Set<String> findCheckedResource(Long roleId) {
        return roleResourceMapper.selectResourceNoByRoleId(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateRole(RoleDto roleDto) {
        Role role = BeanUtil.toBean(roleDto, Role.class);
        roleMapper.updateByPrimaryKeySelective(role);
        if (ObjectUtil.isEmpty(roleDto.getCheckedResourceNos())) {
            return true;
        }
        roleResourceMapper.deleteRoleResourceByRoleId(role.getId());
        //保存角色资源中间信息
        List<RoleResource> roleResourceList = Lists.newArrayList();
        Arrays.asList(roleDto.getCheckedResourceNos()).forEach(n -> {
            RoleResource roleResource = RoleResource.builder()
                    .roleId(role.getId())
                    .resourceNo(n)
                    .dataState(SuperConstant.DATA_STATE_0)
                    .build();
            roleResourceList.add(roleResource);
        });
        //如果集合为空，则结束请求
        if (EmptyUtil.isNullOrEmpty(roleResourceList)) {
            return true;
        }
        //批量保存角色和资源的关系数据
        roleResourceMapper.batchInsert(roleResourceList);
        return true;
    }

    @Override
    public int deleteRole(Long roleId) {
        // 删除角色与菜单关联
        roleResourceMapper.deleteRoleResourceByRoleId(roleId);
        return roleMapper.deleteByPrimaryKey(roleId);
    }

    @Override
    public List<RoleVo> findRoleVoListInUserId(List<Long> userIds) {
        // 1. 查询数据库获取Role实体列表
        List<Role> roleList = roleMapper.findRoleVoListInUserId(userIds);

        // 2. 将Role实体转换为RoleVo值对象
        return roleList.stream()
                .map(role -> {
                    RoleVo roleVo = new RoleVo();
                    // 手动映射所有字段
                    roleVo.setId(role.getId());
                    roleVo.setRoleName(role.getRoleName());
                    roleVo.setLabel(role.getLabel());
                    roleVo.setUserId(role.getUserId()); // 确保这个字段有setter方法
                    roleVo.setDataState(role.getDataState());
                    roleVo.setRemark(role.getRemark());
                    roleVo.setDataScope(role.getDataScope());
                    // ... 映射其他需要的字段
                    return roleVo;
                })
                .collect(Collectors.toList());
    }

    @Override
    public List<RoleVo> findAllRoles() {
        // 查询所有有效角色
        List<Role> roleList = roleMapper.selectAllValidRoles();

        // 转换为VO
        return roleList.stream()
                .map(role -> {
                    RoleVo roleVo = RoleVo.builder()
                            .id(role.getId())
                            .dataState(role.getDataState())
                            .roleName(role.getRoleName())
                            .label(role.getLabel())
                            .sortNo(role.getSortNo())
                            .dataScope(role.getDataScope())
                            .userId(role.getUserId())
                            .build();

                    // 设置BaseEntity中的字段
                    roleVo.setCreateBy(role.getCreateBy());
                    roleVo.setCreateTime(role.getCreateTime());
                    roleVo.setUpdateBy(role.getUpdateBy());
                    roleVo.setUpdateTime(role.getUpdateTime());
                    roleVo.setRemark(role.getRemark());

                    // 设置默认值或空值
                    roleVo.setCheckedDeptNos(new String[0]);
                    roleVo.setCheckedIds(new String[0]);
                    roleVo.setCheckedResourceNos(new String[0]);

                    return roleVo;
                })
                .collect(Collectors.toList());
    }
}
